package com.ibeeking.found.upms.b.rest.service.impl;

import com.ibeeking.found.upms.b.rest.service.ICsRolePermissionService;
import com.ibeeking.found.upms.b.rest.service.ICsRoleService;
import com.ibeeking.found.upms.service.common.bo.CsRolePermissionBO;
import com.ibeeking.found.upms.service.common.dos.CsRolePermissionDO;
import com.ibeeking.found.upms.service.common.param.RolePermissionParam;
import com.ibeeking.found.upms.service.mapper.CsRolePermissionMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName CsRolePermissionServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-05-10 9:54
 **/
@Service
public class CsRolePermissionServiceImpl implements ICsRolePermissionService {

    @Resource
    private CsRolePermissionMapper csRolePermissionMapper;
    @Resource
    private ICsRoleService csRoleServiceImpl;

    @Transactional(rollbackFor = {BusinessException.class})
    @Override
    public Boolean modifyPermissionByRoleId(RolePermissionParam param) {
        Long administratorId = csRoleServiceImpl.selectAdministratorId();
        if (administratorId.equals(param.getRoleId())) {
            return true;
        }
        csRolePermissionMapper.delete(new LambdaQueryWrapper<>(CsRolePermissionDO.class)
                .eq(CsRolePermissionDO::getRoleId, param.getRoleId())
        );

        if (null == param.getPermissionIds() || 0 == param.getPermissionIds().length) {
            return true;
        }
        List<Long> paramIds = Arrays.asList(param.getPermissionIds());
        //新增关系
        List<CsRolePermissionDO> saves = new ArrayList<>();
        paramIds.parallelStream().forEach(key -> {
            CsRolePermissionDO rolePermissionDO = new CsRolePermissionDO();
            rolePermissionDO.setRoleId(param.getRoleId());
            rolePermissionDO.setPermissionId(key);

            saves.add(rolePermissionDO);
        });
        csRolePermissionMapper.insertBatchSomeColumn(saves);
        return true;
    }

    @Override
    public List<CsRolePermissionBO> queryPermissionIdsByRoleId(Long roleId) {
        List<CsRolePermissionDO> rolePermissionDOS = csRolePermissionMapper.selectList(new LambdaQueryWrapper<>(CsRolePermissionDO.class).eq(CsRolePermissionDO::getRoleId, roleId));
        if (Collections3.isEmpty(rolePermissionDOS)) {
            return Collections3.emptyList();
        }
        return JsonUtils.jsonToList(rolePermissionDOS, CsRolePermissionBO.class);
    }
}
